package joc.internal.transformer;

import javassist.CtBehavior;
import javassist.CtClass;
import joc.PostConditionHook;

public class CustomPostHookBehaviorTransformer extends CustomHookBehaviorTransformer {
	public CustomPostHookBehaviorTransformer(Transformer transformer) {
		super(transformer);
	}

	@Override
	public void transform(CtClass clazz, CtBehavior behavior) throws Exception {
		getLogger().info("behavior " + behavior.getLongName());
		for (CtBehavior consultedBehavior : getConsultedBehaviors(behavior)) {
			getLogger().info("consulted behavior " + consultedBehavior.getLongName());
			if (consultedBehavior.hasAnnotation(PostConditionHook.class)) {
				PostConditionHook annotation = (PostConditionHook) consultedBehavior
						.getAnnotation(PostConditionHook.class);
				handleHooks(behavior, annotation);
			} else if (consultedBehavior.hasAnnotation(PostConditionHook.List.class)) {
				PostConditionHook.List listAnnotation = (PostConditionHook.List) consultedBehavior
						.getAnnotation(PostConditionHook.List.class);
				for (PostConditionHook annotation : listAnnotation.value()) {
					handleHooks(behavior, annotation);
				}
			}
		}
	}

	protected void handleHooks(CtBehavior behavior, PostConditionHook annotation) throws Exception {
		for (Class<?> hookClass : annotation.value()) {
			applyHook(behavior, hookClass.getName(), annotation.id());
		}
	}
}
